package com.googlecode.cswish.view;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.cswish.model.PageInfo;
import com.googlecode.cswish.model.TextModel;
import com.googlecode.cswish.struts.spring.ObjectFactory;
import com.googlecode.cswish.util.BlankObject;
import com.opensymphony.xwork2.ActionContext;

public class DataGridHelper {

	private static final Log logger = LogFactory.getLog(DataGridHelper.class);
	
	public static Object findData(String itemName, Object oTextMode, String itemType) {
		// look up the data source
		Object theValue = ActionContext.getContext().getValueStack().findValue(itemName);
		
		PageInfo<Object> pageInfo = null;
		Collection<Object> dataList = null;
		if (theValue == null || theValue instanceof Collection) {
			dataList = (Collection<Object>) theValue;
			
			if (dataList == null) {
				// loger error
				dataList = BlankObject.Collection;
			}
			
			TextModel textMode = TextModel.toTextModel(oTextMode);
			// switch to read-only page
			if (textMode == TextModel.TRUE || textMode == TextModel.TRUE_WITH_VALUE) {
				pageInfo = new PageInfo<Object>(dataList.size());
				pageInfo.setData(new ArrayList<Object>(dataList));
				pageInfo.setPageSize(dataList.size() == 0 ? 1 : dataList.size());
				pageInfo.setTotalCount(dataList.size());
			} else {
				// adjust the default value if it's in edit model
				if (dataList.size() == 0) {
					// create dummy data
					// give a default init object
					String modelName = itemType;
					dataList = new ArrayList(1);
					try {
						Object instance = ObjectFactory.getInstance().buildModel(modelName, null);
						dataList.add(instance);
					} catch (Exception ex) {
						logger.error("Can't create instance:" + modelName, ex);
					}
				}
			}
		} else if (theValue instanceof PageInfo) {
			pageInfo = (PageInfo) theValue;
			dataList = pageInfo.getData();
		}
		
		if (pageInfo == null) {
			return dataList;
		} else {
			return pageInfo;
		}
	}
}
